package com.itheima.auth.filter;

import com.itheima.cst.SysConsts;
import com.itheima.pojo.MyUser;
import com.itheima.utils.JwtTokenUtil;
import com.itheima.utils.RedisUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//19点17分
public class TokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //String token = request.getHeader("Authorization");
        String token = request.getHeader("Authorization") == null ? request.getParameter("token") : request.getHeader("Authorization");
        if(!ObjectUtils.isEmpty(token)){
            try {
                String username = JwtTokenUtil.parseToken(token);
                //查询当前登入用户信息
                MyUser user = RedisUtil.get(SysConsts.REDIS_USER_PREFIX + username);
                //身份信息
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        username,
                        null,
                        //要获取它的身份，从redis在查一次,它的身份
                        AuthorityUtils.commaSeparatedStringToAuthorityList(user.getAuthority())
                );
                //往下传递身份信息 ThreadLocal
                SecurityContextHolder.getContext().setAuthentication(authentication);

            } catch (Exception e) {
                e.printStackTrace();
                //将异常往外抛
                throw new RuntimeException(e);
            }
        }
        filterChain.doFilter(request,response);
    }
}
